package com.xmb.common.service.wx.impl;

import com.xmb.common.constants.PayStatusEnum;
import com.xmb.common.dao.XmbWechatPaymentOrderMapper;
import com.xmb.common.entity.XmbWechatPaymentOrder;
import com.xmb.common.params.WxPayUnifiedOrdeParam;
import com.xmb.common.service.SnowflakeIdWorker;
import com.xmb.common.service.wx.WxCommonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * Created by lyndon on 2019/6/6.
 * 获取外部订单编号: 长度最长为32位
 */
@Service
public class WxCommonServiceImpl implements WxCommonService{

    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    @Resource
    private XmbWechatPaymentOrderMapper wechatPaymentOrderMapper;

    @Override
    public String getPayOutTranceNo(String PayPrefix) {
        return PayPrefix+"_"+this.getBaseTranceNo();
    }

    @Override
    public String getRefundOutTranceNo() {
        return "REFUND"+"_"+this.getBaseTranceNo();
    }

    @Override
    public String getRedOutTranceNo() {
        return "RED"+"_"+this.getBaseTranceNo();
    }

    @Override
    public String getEntPayOutTranceNo() {
        return "ENT_PAY"+"_"+this.getBaseTranceNo();
    }


    @Override
    public Boolean checkPayStatus(WxPayUnifiedOrdeParam ordeParam) {
        XmbWechatPaymentOrder paymentOrder = new XmbWechatPaymentOrder();
        paymentOrder.setSenceId(ordeParam.getOrderId());
        paymentOrder.setSenceType(ordeParam.getOrderType());
        paymentOrder.setPayStatus(PayStatusEnum.paid.name());
        XmbWechatPaymentOrder wechatPaymentOrder = wechatPaymentOrderMapper.selectBySenceIdAndType(paymentOrder);
        return wechatPaymentOrder != null;
    }

    private String getBaseTranceNo() {
        String nextId = String.valueOf(snowflakeIdWorker.getNextId());
        return LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))
                + "_"
                + nextId.substring(nextId.length() - 6,nextId.length());
    }
}
